/*
 * Created on May 7, 2004
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.pyant.tasks;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.Commandline;
import org.apache.tools.ant.types.FileSet;


/**
 * @author Ron Smith
 *
 * <py-test pythonpathref="project.python.path" >
 *   <fileset dir="testscripts2">
 *     <include name="** /*Test.py"/>
 *   </fileset>
 * </py-test>
 *
 */
public class PythonTestTask extends PythonInteractiveBaseTask
{
	protected ArrayList filesets = new ArrayList();
	protected File dir = null;

	private final static String FAIL_MSG = "Test execution failed.  See output for details.";

	public void execute()
	{
		Project project = getProject();
		project.log("PythonTestTask.execute()", Project.MSG_DEBUG);
		Commandline cmdline = new Commandline();
		cmdline.setExecutable("python");

		String modulesArg = getModulesArg(project);
		String script = "import unittest\n";
//		script += "import " + modulesArg.replaceAll("'", "") +"\n";
		script += "\nunittest.main(module=None, defaultTest=None, argv=[" + modulesArg + "])";

		this.script = script;
		System.out.println("Executing\n\t" + script);
		super.executeScript(project, this.dir, FAIL_MSG);

	}

	/**
	 *
	 * @param project
	 */
	protected String getModulesArg(Project project) {
		StringBuffer modulesArg = new StringBuffer();
		boolean isFirst = true;
		Iterator fsIter = filesets.iterator();
		while(fsIter.hasNext())
		{
			FileSet fs = (FileSet)fsIter.next();
			DirectoryScanner ds = fs.getDirectoryScanner(project);
			String[] files = ds.getIncludedFiles();
			for(int i = 0; i < files.length; i++)
			{
				project.log(files[i]);
				if(files[i].endsWith(".py"))
				{
					String fileName = files[i].substring(0, files[i].length()-3);
					if (!this.packagedtests) {
						fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1);
					}
					if(isFirst)
					{
						modulesArg.append("'" + fileName + "'");
						isFirst = false;
					}
					modulesArg.append(",'" + fileName + "'");
			 	}
			}
		}

		String retVal = modulesArg.toString();

		retVal = retVal.replace('\\', '.');
		retVal = retVal.replace('/', '.');
		project.log("Modules: " + retVal);
		return (retVal);
	}

	protected boolean packagedtests = true;

	public void setPackagedtests(boolean t) {
		this.packagedtests = t;
	}

	public void addFileSet(FileSet fs)
	{
		this.filesets.add(fs);
	}

	public void setDir(File dir)
	{
		this.dir = dir;
	}

}